package admin

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"zhuandan/data_source"
	"zhuandan/models"
)

type TemplatelistRBody struct {
	Data       []models.Template `json:"data"`
	PageNo     int               `json:"pageNo"`
	PageSize   int               `json:"pageSize"`
	TotalCount int64             `json:"totalCount"`
	TotalPage  int64             `json:"totalPage"`
}

type TemplatelistBody struct {
	Page     int    `json:"pageNo" from:"pageNo"`
	Pagesize int    `json:"pageSize" from:"pageSize"`
	Title    string `json:"title" gorm:"title"`
}

func Templatelist(ctx *gin.Context) {
	request := TemplatelistBody{}
	ctx.ShouldBind(&request)
	title := request.Title

	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Template
	res := data_source.Db
	if title != "" {
		res = res.Where("title like ? or content like ?", "%"+title+"%", "%"+title+"%")
	}

	res.Model(&models.Template{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := TemplatelistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type TemplateBody struct {
	ID      int64  `gorm:"column:id" json:"id"`
	Title   string `json:"title" gorm:"title"`
	Content string `json:"content" gorm:"content"`
}

func Templateadd(ctx *gin.Context) {
	request := TemplateBody{}
	ctx.ShouldBind(&request)
	title := request.Title
	content := request.Content
	ty := models.Template{
		Content: content,
		Title:   title,
	}
	data_source.Db.Create(&ty)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Templateupdate(ctx *gin.Context) {
	request := TemplateBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	title := request.Title
	content := request.Content
	ty := models.Template{
		Content: content,
		Title:   title,
	}
	data_source.Db.Where("id = ?", id).Updates(&ty)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Templatedel(ctx *gin.Context) {
	request := BanneraddBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	data_source.Db.Where("id = ?", id).Delete(&models.Template{})
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
